package com.example.online.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.online.music.common.R;
import com.example.online.music.model.domain.UserGroup;
import com.example.online.music.service.IGroupService;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

import static com.example.online.music.controller.FaceController.HTTP_CLIENT;

@RestController
@RequestMapping("/group")
@CrossOrigin(origins = "*", maxAge = 3600)
public class GroupController {
    @Autowired
    IGroupService groupService;

    @GetMapping("/list")
    public R list() {
        return R.success("用户组获取成功",groupService.list());
    }

    @PostMapping("/add")
    public R add(@RequestBody Map<String, String> map) {
        String groupId = map.get("groupId");
        String token = map.get("token");
        R R = UserGroup.judgeValid(groupId);
        if (!Objects.equals(R.getCode(), 200)) {
            return R;
        }

        MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("group_id", groupId);

        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, jsonObject.toJSONString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add?access_token=" + token)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            JSONObject res = JSONObject.parseObject(Objects.requireNonNull(response.body()).string());
            Integer errorCode = (Integer) res.get("error_code");
            if (errorCode == 0) {
                UserGroup group = new UserGroup();
                group.setGroupId(groupId);
                group.setUserNumber(0);
                group.setCreateTime(new Date() + "");
                groupService.save(group);
                return R.success( "用户组添加成功",null);
            } else if (errorCode == 223101) {
                return R.error("该用户组已存在, 请重新添加");
            }
            return R.error("未知错误, 用户组添加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("用户组添加失败");
        }
    }
}